﻿
PageEditor = function(contentRegion,currentPageId) {
    this.region = '#'+contentRegion;
    this.pageId = currentPageId;
    this.editorialPart = "<div class='editorzone'>" 
        + " <img src='{1}/Content/icons/application_edit.png' title='Edit Page' onclick='UpdateContent({0})' /> " 
        + " <img src='{1}/Content/icons/application_delete.png' title='Delete Page' onclick='DeleteContent({0})' /> " 
        + " <img src='{1}/Content/icons/email_open.png' title='Email this page' onclick='EmailContent({0})' /> " 
        + " </div>";
    this.editor = "<textarea id='editor-{0}' style='display:none' ></textarea>";
    
    this.iterateContent();
    
}

PageEditor.prototype = {

    iterateContent: function() {
        console.log("Editor started for " + this.region + " on page : " + this.pageId);
        var me = this;
        $(this.region).find("li div").each(function(item, data) {
            console.log("item found: " + item);
           // $(this).css({ border: 'solid 1px #FF0000' });
            id = this.id ;
            id = id.split("-")[1];
            
            $(this).prepend( String.format( me.editorialPart , id , serverBase));
            $(this).parent().append( String.format( me.editor , id ) ) ;
            
            $(this).hover( 
                function(){ 
                        zone = $(this).find('.editorzone').show();
                        zone.css({left: ($(this).position().left+$(this).width() - 110)+"px" , top: ($(this).position().top-25)+"px"});
                        $(this).addClass("dotted");
                    } 
                , function(){$(this).find('.editorzone').hide();$(this).removeClass('dotted');} 
                );
            $(this).bind( 'dblclick' , function(){UpdateContent(id)});
        });
    },   

}
function DeleteContent( id ) 
{
    $.post(serverBase + "Content/delete/"+id , { id : id},function(response){ alert(" Content deleted " + id ); } );
}

function EmailContent( id ) 
{
    alert(" Content will be deleted " + id );
}
function UpdateContent( id ) 
{
    var contentId = "#pcd-" + id ;
    var textAreaId = "#editor-" + id ;
    
    mySettings.onSave = function(markItUp) {
        data = markItUp.textarea.value;
        ok = confirm("Save the content for ID: " + id );
        if (!ok) {
          return false;
        }
        
        $.post( 
            serverBase + "Content/Index/" + id 
            , { data : $(textAreaId).val() } 
            , function(response){
                 alert( "Save completed for id: " + id );
                 $(contentId).text( response) ;
            }   
        );
    }
    
    $.get( serverBase + "Content/Get/" + id  , function(response){
        $(textAreaId).show();
        $(textAreaId).val(response);
        $(contentId).text('');
        $(textAreaId).markItUp( mySettings );
         
    });
    
    
    
}
